<template>
    <div class="permission-management">
        <div class="page-header">
            <h1>权限管理</h1>
            <a-button type="primary" @click="showAddModal = true">
                <template #icon>
                    <PlusOutlined />
                </template>
                添加权限
            </a-button>
        </div>

        <!-- 搜索和筛选 -->
        <div class="search-section">
            <a-row :gutter="16">
                <a-col :span="6">
                    <a-input-search v-model:value="searchKeyword" placeholder="搜索权限名称或编码" @search="handleSearch" />
                </a-col>
                <a-col :span="4">
                    <a-select v-model:value="selectedType" placeholder="选择类型" style="width: 100%"
                        @change="handleTypeChange">
                        <a-select-option value="">全部类型</a-select-option>
                        <a-select-option value="0">目录</a-select-option>
                        <a-select-option value="1">菜单</a-select-option>
                        <a-select-option value="2">按钮</a-select-option>
                        <a-select-option value="3">接口</a-select-option>
                    </a-select>
                </a-col>
                <a-col :span="4">
                    <a-button @click="resetFilters">重置筛选</a-button>
                </a-col>
            </a-row>
        </div>

        <!-- 权限列表 - 树形表格 -->
        <div class="permission-table">
            <a-table 
                :columns="columns" 
                :data-source="filteredTree" 
                :loading="loading"
                row-key="id"
                :childrenColumnName="'children'"
                :indentSize="30"
                :defaultExpandAllRows="true"
            >
                <template #bodyCell="{ column, record }">
                    <template v-if="column.key === 'type'">
                        <a-tag :color="getTypeColor(record.type)">
                            {{ getTypeText(record.type) }}
                        </a-tag>
                    </template>
                    <template v-else-if="column.key === 'status'">
                        <a-tag :color="record.deleted === 0 ? 'green' : 'red'">
                            {{ record.deleted === 0 ? '正常' : '禁用' }}
                        </a-tag>
                    </template>
                    <template v-else-if="column.key === 'parentId'">
                        {{ record.parentId === 0 ? '顶级' : getParentName(record.parentId) }}
                    </template>
                    <template v-else-if="column.key === 'action'">
                        <a-space>
                            <a-button type="link" @click="editPermission(record)">编辑</a-button>
                            <a-button type="link" @click="viewPermission(record)">查看</a-button>
                            <a-popconfirm title="确定要删除这个权限吗？" @confirm="deletePermission(record.id)">
                                <a-button type="link" danger>删除</a-button>
                            </a-popconfirm>
                        </a-space>
                    </template>
                </template>
            </a-table>
        </div>

        <!-- 添加/编辑权限弹窗 -->
        <a-modal v-model:open="showAddModal" :title="isEditing ? '编辑权限' : '添加权限'" width="600px" @ok="handleSubmit"
            @cancel="handleCancel">
            <a-form ref="formRef" :model="permissionForm" :rules="formRules" layout="vertical">
                <a-row :gutter="16">
                    <a-col :span="12">
                        <a-form-item label="权限名称" name="name">
                            <a-input v-model:value="permissionForm.name" placeholder="请输入权限名称" />
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item label="权限编码" name="code">
                            <a-input v-model:value="permissionForm.code" placeholder="请输入权限编码" />
                        </a-form-item>
                    </a-col>
                </a-row>

                <a-row :gutter="16">
                    <a-col :span="12">
                        <a-form-item label="权限类型" name="type">
                            <a-select v-model:value="permissionForm.type" placeholder="选择权限类型">
                                <a-select-option value="0">目录</a-select-option>
                                <a-select-option value="1">菜单</a-select-option>
                                <a-select-option value="2">按钮</a-select-option>
                                <a-select-option value="3">接口</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item label="父级权限" name="parentId">
                            <a-tree-select
                                v-model:value="permissionForm.parentId"
                                :tree-data="permissionTree"
                                placeholder="选择父级权限"
                                allow-clear
                                :field-names="{ children: 'children', label: 'name', value: 'id' }"
                            />
                        </a-form-item>
                    </a-col>
                </a-row>

                <a-row :gutter="16">
                    <a-col :span="12">
                        <a-form-item label="菜单路径" name="url">
                            <a-input v-model:value="permissionForm.url" placeholder="请输入菜单路径" />
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item label="菜单图标" name="icon">
                            <a-input v-model:value="permissionForm.icon" placeholder="请输入菜单图标" />
                        </a-form-item>
                    </a-col>
                </a-row>

                <a-form-item label="排序" name="sort">
                    <a-input-number v-model:value="permissionForm.sort" :min="0" style="width: 100%" />
                </a-form-item>
            </a-form>
        </a-modal>
    </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { 
    getAllMenu,
    addMenu,
    updateMenu,
    deleteMenu as deleteMenuApi
} from '@/api/user/sysPermissionController'

// 响应式数据
const loading = ref(false)
const searchKeyword = ref('')
const selectedType = ref('')
const showAddModal = ref(false)
const isEditing = ref(false)
const flatPermissions = ref([]) // 存储原始扁平数据
const permissionTreeData = ref([]) // 存储树形结构数据

// 权限表单
const permissionForm = reactive({
    id: undefined,
    name: '',
    code: '',
    type: 1,
    parentId: 0,
    sort: 0,
    url: '',
    icon: ''
})

// 表单验证规则
const formRules = {
    name: [{ required: true, message: '请输入权限名称' }],
    code: [{ required: true, message: '请输入权限编码' }],
    type: [{ required: true, message: '请选择权限类型' }]
}

// 表格列配置
const columns = [
    {
        title: '权限名称',
        dataIndex: 'name',
        key: 'name',
        width: 150
    },
    {
        title: '权限编码',
        dataIndex: 'code',
        key: 'code',
        width: 150
    },
    {
        title: '权限类型',
        dataIndex: 'type',
        key: 'type',
        width: 100
    },
    {
        title: '父级权限',
        dataIndex: 'parentId',
        key: 'parentId',
        width: 100
    },
    {
        title: '菜单路径',
        dataIndex: 'url',
        key: 'url',
        width: 150
    },
    {
        title: '排序',
        dataIndex: 'sort',
        key: 'sort',
        width: 80
    },
    {
        title: '状态',
        dataIndex: 'deleted',
        key: 'status',
        width: 80
    },
    {
        title: '创建时间',
        dataIndex: 'createTime',
        key: 'createTime',
        width: 150
    },
    {
        title: '操作',
        key: 'action',
        width: 200,
        fixed: 'right'
    }
]

// 计算属性
const permissionTree = computed(() => {
    return buildPermissionTree(flatPermissions.value)
})

// 树形数据筛选
const filteredTree = computed(() => {
    if (!searchKeyword.value && !selectedType.value) {
        return permissionTreeData.value
    }
    return filterTree(permissionTreeData.value, searchKeyword.value, selectedType.value)
})

// 方法
const loadPermissions = async () => {
    loading.value = true
    try {
        const response = await getAllMenu()
        if (response && response.code === '00000') {
            flatPermissions.value = response.data || []
            // 构建树形结构
            permissionTreeData.value = buildPermissionTree(flatPermissions.value)
        } else {
            message.error('获取权限列表失败')
        }
    } catch (error) {
        console.error('获取权限列表失败:', error)
        message.error('获取权限列表失败')
    } finally {
        loading.value = false
    }
}

// 构建树形结构
const buildPermissionTree = (list) => {
    const map = {}
    const roots = []
    
    // 创建所有节点的映射
    list.forEach(item => {
        map[item.id] = { ...item, children: [] }
    })
    
    // 构建树形结构
    list.forEach(item => {
        const parentId = item.parentId
        if (parentId !== 0 && map[parentId]) {
            map[parentId].children.push(map[item.id])
        } else {
            roots.push(map[item.id])
        }
    })
    
    return roots
}

// 树形数据筛选函数
const filterTree = (tree, keyword, type) => {
    if (!tree || tree.length === 0) return []
    
    return tree
        .map(node => {
            // 克隆节点以避免修改原始数据
            const newNode = { ...node }
            
            // 递归筛选子节点
            if (newNode.children && newNode.children.length > 0) {
                newNode.children = filterTree(newNode.children, keyword, type)
            }
            
            // 检查节点是否匹配条件
            const keywordMatch = !keyword || 
                (newNode.name && newNode.name.toLowerCase().includes(keyword.toLowerCase())) || 
                (newNode.code && newNode.code.toLowerCase().includes(keyword.toLowerCase()))
            
            const typeMatch = !type || newNode.type.toString() === type
            
            // 如果节点本身匹配，或者有匹配的子节点，则保留
            const hasMatchedChildren = newNode.children && newNode.children.length > 0
            const isMatched = keywordMatch && typeMatch
            
            if (isMatched || hasMatchedChildren) {
                return newNode
            }
            return null
        })
        .filter(node => node !== null)
}

const getParentName = (parentId) => {
    const parent = flatPermissions.value.find(p => p.id === parentId)
    return parent ? parent.name : '未知'
}

const getTypeColor = (type) => {
    const colors = {
        0: 'blue',    // 目录
        1: 'green',   // 菜单
        2: 'orange',  // 按钮
        3: 'purple'   // 接口
    }
    return colors[type] || 'default'
}

const getTypeText = (type) => {
    const texts = {
        0: '目录',
        1: '菜单',
        2: '按钮',
        3: '接口'
    }
    return texts[type] || '未知'
}

const handleSearch = () => {
    // 搜索逻辑在计算属性中处理
}

const handleTypeChange = () => {
    // 类型筛选逻辑在计算属性中处理
}

const resetFilters = () => {
    searchKeyword.value = ''
    selectedType.value = ''
}

const editPermission = (permission) => {
    isEditing.value = true
    Object.assign(permissionForm, permission)
    showAddModal.value = true
}

const viewPermission = (permission) => {
    message.info(`查看权限: ${permission.name}`)
}

const deletePermission = async (permissionId) => {
    try {
        const response = await deleteMenuApi({ id: permissionId })
        if (response && response.code === '00000') {
            message.success('删除权限成功')
            await loadPermissions()
        } else {
            message.error('删除权限失败')
        }
    } catch (error) {
        console.error('删除权限失败:', error)
        message.error('删除权限失败')
    }
}

const handleSubmit = async () => {
    try {
        if (isEditing.value) {
            // 编辑权限
            const response = await updateMenu(permissionForm)
            if (response && response.code === '00000') {
                message.success('更新权限成功')
                await loadPermissions()
            } else {
                message.error('更新权限失败')
            }
        } else {
            // 添加权限
            const response = await addMenu(permissionForm)
            if (response && response.code === '00000') {
                message.success('添加权限成功')
                await loadPermissions()
            } else {
                message.error('添加权限失败')
            }
        }

        showAddModal.value = false
        resetForm()
    } catch (error) {
        console.error('操作失败:', error)
    }
}

const handleCancel = () => {
    showAddModal.value = false
    resetForm()
}

const resetForm = () => {
    Object.assign(permissionForm, {
        id: undefined,
        name: '',
        code: '',
        type: 1,
        parentId: 0,
        sort: 0,
        url: '',
        icon: ''
    })
    isEditing.value = false
}

// 生命周期
onMounted(async () => {
    await loadPermissions()
})
</script>

<style scoped>
.permission-management {
    padding: 20px;
    background-color: #f5f7fa;
    min-height: 100vh;
}

.page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    padding: 16px 24px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.09);
}

.page-header h1 {
    margin: 0;
    color: #1f2d3d;
    font-size: 20px;
    font-weight: 600;
}

.search-section {
    background: #fff;
    padding: 16px 24px;
    border-radius: 8px;
    margin-bottom: 16px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.09);
}

.permission-table {
    background: #fff;
    border-radius: 8px;
    padding: 16px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.09);
    overflow: hidden;
}

/* 树形表格样式增强 */
:deep(.ant-table-tbody > tr) {
    transition: all 0.3s;
}

:deep(.ant-table-tbody > tr:hover) {
    background-color: #f0f7ff !important;
}

:deep(.ant-table-row-expand-icon) {
    background-color: #fff;
    border: 1px solid #d9d9d9;
}

/* 操作按钮样式 */
:deep(.ant-btn-link) {
    padding: 0 4px;
}
</style>